﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Configuration;
using System.Collections;
using System.Web.Security;

namespace TireService.Web.UserControls
{
    public partial class ucServiceCarScheduleDetailDayPlanning : System.Web.UI.UserControl
    {
        private string _controlname = "DayPlanner";

        //public int ServiceCarId
        //{
        //    get
        //    {
        //        if (ViewState["_servicecarid"] != null)
        //            return (int)ViewState["_servicecarid"];
        //        else
        //            return 0;
        //    }
        //    set
        //    {
        //        ViewState["_servicecarid"] = value;
        //    }
        //}

        //public DateTime ScheduleDate
        //{
        //    get
        //    {
        //        if (ViewState["_scheduledate"] != null)
        //            return (DateTime)ViewState["_scheduledate"];
        //        else
        //            return DateTime.MinValue;
        //    }
        //    set
        //    {
        //        ViewState["_scheduledate"] = value;
        //    }
        //}

        //public Boolean UserControlLoaded
        //{
        //    get
        //    {
        //        if (ViewState["_availablecapacityloaded"] != null)
        //            return (Boolean)ViewState["_availablecapacityloaded"];
        //        else
        //            return false;
        //    }
        //    set
        //    {
        //        ViewState["_availablecapacityloaded"] = value;
        //    }
        //}

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToBoolean(Session["UserControlLoaded" + _controlname]))
            {
                LoadUserControl(Convert.ToInt32(Session["ServiceCarId" + _controlname]), Convert.ToDateTime(Session["ScheduleDate" + _controlname]));
            }
        }

        protected void callbackDayPlanPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            // Get values from client (0: ServiceCarId, 1: ScheduleDate)
            string[] param = e.Parameter.Split('|');

            Session["ServiceCarId" + _controlname] = Convert.ToInt32(param[0]);
            Session["ScheduleDate" + _controlname] = Convert.ToDateTime(param[1]);
            //this.ServiceCarId = Convert.ToInt32(param[0]);
            //this.ScheduleDate = Convert.ToDateTime(param[1]);

            //LoadUserControl(ServiceCarId, ScheduleDate);
            LoadUserControl(Convert.ToInt32(Session["ServiceCarId" + _controlname]), Convert.ToDateTime(Session["ScheduleDate" + _controlname]));
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int ServiceCarId, DateTime ScheduleDate)
        {
            // Load form data
            if (ServiceCarId != 0 & ScheduleDate != null)
            {
                LoadDayPlan(ServiceCarId, ScheduleDate);
            }
            else
            {
                //// Error
                //throw new ArgumentException("Dagsplan blev ikke fundet");
            }
        }

        public string ShowWeekDay(DayOfWeek DayName)
        {
            string dayname = "";
            if (DayName == DayOfWeek.Monday)
            {
                dayname = "Mandag";
            }
            if (DayName == DayOfWeek.Tuesday)
            {
                dayname = "Tirsdag";
            }
            if (DayName == DayOfWeek.Wednesday)
            {
                dayname = "Onsdag";
            }
            if (DayName == DayOfWeek.Thursday)
            {
                dayname = "Torsdag";
            }
            if (DayName == DayOfWeek.Friday)
            {
                dayname = "Fredag";
            }
            if (DayName == DayOfWeek.Saturday)
            {
                dayname = "Lørdag";
            }
            if (DayName == DayOfWeek.Sunday)
            {
                dayname = "Søndag";
            }

            return dayname;
        }

        public void LoadDayPlan(int ServiceCarId, DateTime ScheduleDate)
        {
            lblDateInformation.Text = "Dato: " + ShowWeekDay(ScheduleDate.DayOfWeek) + " " + ScheduleDate.ToShortDateString() + " / Servicebil: " + ServiceCarId.ToString();

            TireServiceDB db = new TireServiceDB();
            
            // Check if any geographical areas is allocated
            ServiceCarGeographicalAreaAllocation areaallocation = db.GetServiceCarGeographicalAreaAllocation(ServiceCarId, ScheduleDate);
            if (areaallocation != null)
            {
                lblAreaAllocationInformation.Text = "Område: " + db.GetServiceGeographicalAreaDescription(areaallocation.ServiceGeoAreaId);
                cbAllowAllocationOutsideGeographicalArea.Enabled = true;
            }
            else
            {
                lblAreaAllocationInformation.Text = "Område: Ikke tildelt et område";
                cbAllowAllocationOutsideGeographicalArea.Enabled = false;
            }

            // Check if group booking
            bool GroupBooking = db.IsServiceCarScheduleGroupBooking(ServiceCarId, ScheduleDate);
            if (GroupBooking)
            {
                lblGroupBooking.Text = "Gruppe booking";
            }
            else
            {
                lblGroupBooking.Text = "";
            }

            gvDayPlan.DataSource = db.ServiceCarScheduleDetailViews.Where(p => p.ServiceCarId == ServiceCarId & p.ScheduleDate == ScheduleDate).OrderBy(d => d.StartTime).ToList();
            gvDayPlan.DataBind();

            Session["UserControlLoaded" + _controlname] = true;
        }

        /// <summary>
        /// Postback function that updates overview of capacity on specific service car and date
        /// </summary>
        protected void gvDayPlan_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            //LoadDayPlan(this.ServiceCarId, this.ScheduleDate);
            LoadUserControl(Convert.ToInt32(Session["ServiceCarId" + _controlname]), Convert.ToDateTime(Session["ScheduleDate" + _controlname]));
        }

        /// <summary>
        /// Gridview function that runs when databinding - Changes colors based on customerconfirmed value
        /// </summary>
        protected void gvDayPlan_HtmlRowPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
        {
            if (e.RowType != DevExpress.Web.ASPxGridView.GridViewRowType.Data) return;

            int servicetype = Convert.ToInt32(gvDayPlan.GetRowValuesByKeyValue(e.KeyValue, "ScheduleDetailTypeId"));

            if (servicetype == (int)Shared.ScheduleDetailType.Available)
            {
                e.Row.BackColor = System.Drawing.Color.White;
            }
            if (servicetype == (int)Shared.ScheduleDetailType.Blocked)
            {
                e.Row.BackColor = System.Drawing.Color.Red;
            }
            if (servicetype == (int)Shared.ScheduleDetailType.ServiceDrive)
            {
                // Get customerconfirmed value - based on that rows will be formated
                bool CustomerConfirmed = Convert.ToBoolean(gvDayPlan.GetRowValuesByKeyValue(e.KeyValue, "CustomerConfirmed"));

                if (CustomerConfirmed)
                {
                    e.Row.BackColor = System.Drawing.Color.DarkGreen;
                }
                else
                {

                    e.Row.BackColor = System.Drawing.Color.Orange;
                }
            }
        }

        /// <summary>
        /// Callback function that creates a single servicecar capacity record
        /// </summary>
        protected void callCreateSingleServiceCarCapacity_Callback(object sender, CallbackEventArgs e)
        {
            // Get values (servicecarid, scheduledate, duration, overlap)
            string[] param = e.Parameter.Split('|');

            // Save new timeslot          
            int servicecarid = Convert.ToInt32(param[0]);
            DateTime datetime = Convert.ToDateTime(param[1]);

            TireServiceDB db = new TireServiceDB();

            ServiceCarSchedule schedule = db.GetServiceCarSchedule(servicecarid, datetime);

            ServiceCarScheduleDetail lastscheduledetail = schedule.ServiceCarScheduleDetails.OrderBy(p => p.SequenceNumber).Last();

            ServiceCarScheduleDetail scheduledetail = new ServiceCarScheduleDetail();
            schedule.ServiceCarScheduleDetails.Add(scheduledetail);
            scheduledetail.ScheduleDetailTypeId = (int)Shared.ScheduleDetailType.Available;
            scheduledetail.SequenceNumber = lastscheduledetail.SequenceNumber + 1;
            scheduledetail.StartTime = lastscheduledetail.EndTime - TimeSpan.FromMinutes(Convert.ToInt32(param[3]));
            scheduledetail.EndTime = scheduledetail.StartTime.Add(TimeSpan.FromMinutes(Convert.ToInt32(param[2])));

            db.AddServiceCarScheduleDetail(scheduledetail);

            db.SubmitChanges();
        }

        /// <summary>
        /// Callback function that bookes selected servicedrive task into selected servicedetail
        /// </summary>
        protected void callBookService_Callback(object sender, CallbackEventArgs e)
        {
            // Get input parameters from client (0: taskid, 1: servicescheduledetailid, 2: usesecondaryaddress - true/false, 3: customerconfirmed - true/false, 4: note, 5: allow booking outside area - true/false (optional))
            string[] param = e.Parameter.Split('|');

            int TaskId = Convert.ToInt32(param[0]);
            int ServiceCarScheduleDetailId = Convert.ToInt32(param[1]);
            bool UseSecondaryAddress = Convert.ToBoolean(param[2]);
            bool CustomerConfirmed = Convert.ToBoolean(param[3]);
            string Note = param[4];

            TireServiceDB db = new TireServiceDB();

            Task task = db.GetTask(TaskId);
            if (task == null)
            {
                throw new ArgumentException("Ingen servicekørsel valgt - venligst vælg servicekørsel først.");
            }

            // Other validation of Task
            if (task.TaskTypeStatusId == (int)Shared.TaskTypeStatus.ServiceDrive_Cancelled)
            {
                throw new ArgumentException("Service kørsel er annulleret og kan derfor ikke planlægges ind.");
            }
            if (task.TaskTypeStatusId == (int)Shared.TaskTypeStatus.ServiceDrive_Completed)
            {
                throw new ArgumentException("Service kørsel er gennemført/afsluttet og kan derfor ikke planlægges ind.");
            }
            if (task.TaskTypeStatusId == (int)Shared.TaskTypeStatus.ServiceDrive_Planned)
            {
                throw new ArgumentException("Service kørsel er allerede planlagt.");
            }

            // Check if user has selected car from carneedservice gridview
            Car car = db.GetCar(Convert.ToInt32(task.CarId));
            if (car == null)
            {
                throw new ArgumentException("Ingen bil valgt angivet på servicekørsel - booking kan derfor ikke gennemføres.");
            }

            // Get servicecarscheduledetail record
            ServiceCarScheduleDetail scheduledetail = db.GetServiceCarScheduleDetail(ServiceCarScheduleDetailId);
            if (scheduledetail == null)
            {
                throw new ArgumentException("Valgt tidsrum eksistere ikke - venligst prøv igen.");
            }

            // Check if timeslot is "available"
            if (scheduledetail.ScheduleDetailTypeId != (int)Shared.ScheduleDetailType.Available)
            {
                throw new ArgumentException("Valgt tidsrum ikke ledigt - venligst vælg et andet.");
            }

            // Check if area validation is needed
            ServiceCarGeographicalAreaAllocation areaallocation = db.GetServiceCarGeographicalAreaAllocation(scheduledetail.ServiceCarId, scheduledetail.ScheduleDate);
            if (areaallocation != null)
            {
                bool AllowAllocationOutSideArea = Convert.ToBoolean(param[5]);
                if (!AllowAllocationOutSideArea)
                {
                    // Validate
                    if (UseSecondaryAddress)
                    {
                        if (db.ServiceGeographicalAreaZipCodeLists.Where(p => p.ServiceGeoAreaId == areaallocation.ServiceGeoAreaId & p.ZipCode == task.SecondaryZipCode).Count() == 0)
                        {
                            throw new ArgumentException("Adressen ligger ikke i kørselsområdet - venligst vælg en anden dag eller angiv at allokering udenfor område er tilladt.");
                        }
                    }
                    else
                    {
                        if (db.ServiceGeographicalAreaZipCodeLists.Where(p => p.ServiceGeoAreaId == areaallocation.ServiceGeoAreaId & p.ZipCode == task.PrimaryZipCode).Count() == 0)
                        {
                            throw new ArgumentException("Adressen ligger ikke i kørselsområdet - venligst vælg en anden dag eller angiv at allokering udenfor område er tilladt.");
                        }
                    }
                }
            }

            // Insert car on timeslot and update scheduledetail
            scheduledetail.CarId = car.CarId;
            scheduledetail.ToTireSetId = task.TireSetId;
            scheduledetail.CustomerConfirmed = CustomerConfirmed;
            if (UseSecondaryAddress)
            {
                scheduledetail.ToAddress = task.SecondaryAddress;
                scheduledetail.ToZipCode = task.SecondaryZipCode;
                scheduledetail.ToCity = task.SecondaryCity;
                scheduledetail.ToCountryId = task.SecondaryCountryId;
                scheduledetail.ToLatitude = task.SecondaryLatitude;
                scheduledetail.ToLongitude = task.SecondaryLongitude;
            }
            else
            {
                scheduledetail.ToAddress = task.PrimaryAddress;
                scheduledetail.ToZipCode = task.PrimaryZipCode;
                scheduledetail.ToCity = task.PrimaryCity;
                scheduledetail.ToCountryId = task.PrimaryCountryId;
                scheduledetail.ToLatitude = task.PrimaryLatitude;
                scheduledetail.ToLongitude = task.PrimaryLongitude;
            }

            scheduledetail.Note = Note;
            scheduledetail.ScheduleDetailTypeId = (int)Shared.ScheduleDetailType.ServiceDrive;

            //// Create new guid to ensure "earlier" booking is not approved by wrong customer later
            //scheduledetail.DetailGuid = Guid.NewGuid();

            // Fetch all TaskDetails to see if Task contain TireChange
            List<TaskDetail> taskdetails = db.GetTaskDetails(task.TaskId);

            foreach (TaskDetail taskdetail in taskdetails)
            {
                if (taskdetail.TaskDetailTypeId == (int)Shared.TaskDetailType.ServiceDrive_ChangeTire)
                {
                    // Update car with new status        
                    car.CarStatusId = (int)Shared.CarStatus.PlannedTireChange;
                }
            }

            // Relate Task to ServiceCarScheduleDetail
            scheduledetail.TaskId = task.TaskId;

            // Update Task status
            task.TaskTypeStatusId = (int)Shared.TaskTypeStatus.ServiceDrive_Planned;

            // Submit changes to database
            db.SubmitChanges();

            // Dispose database connection
            db.Dispose();
        }

        /// <summary>
        /// Callback function that deletes bookes servicedetail
        /// </summary>
        protected void callDeleteBookedService_Callback(object sender, CallbackEventArgs e)
        {
            // Get input parameters from client (servicescheduledetailid)
            string[] param = e.Parameter.Split('|');

            int ServiceCarScheduleDetailId = Convert.ToInt32(param[0]);

            TireServiceDB db = new TireServiceDB();

            // Get servicecarscheduledetail record
            ServiceCarScheduleDetail scheduledetail = db.GetServiceCarScheduleDetail(ServiceCarScheduleDetailId);
            if (scheduledetail == null)
            {
                throw new ArgumentException("Valgt tidsrum eksistere ikke - venligst prøv igen.");
            }

            // Check if timeslot is booked or blocked
            if (scheduledetail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.Available)
            {
                throw new ArgumentException("Valgt tidsrum er ikke booket - venligst vælg et andet.");
            }

            if (scheduledetail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
            {
                // Get related task
                Task task = db.GetTask(Convert.ToInt32(scheduledetail.TaskId));

                // Change status on task
                task.TaskTypeStatusId = (int)Shared.TaskTypeStatus.ServiceDrive_Replan;

                // Fetch all TaskDetails to see if Task contain TireChange
                List<TaskDetail> taskdetails = db.GetTaskDetails(task.TaskId);

                foreach (TaskDetail taskdetail in taskdetails)
                {
                    if (taskdetail.TaskDetailTypeId == (int)Shared.TaskDetailType.ServiceDrive_ChangeTire)
                    {
                        Car car = db.GetCar(Convert.ToInt32(task.CarId));

                        // Update car with new status        
                        car.CarStatusId = (int)Shared.CarStatus.AwaitsTireChangePlanning;
                    }
                }
            }

            // Update timeslot - reset to available status
            ServiceCarScheduleDetailBLL detailBLL = new ServiceCarScheduleDetailBLL();
            detailBLL.MakeServiceCarScheduleDetailAvailable(db, scheduledetail, true);

            // Commit changes to database
            db.SubmitChanges();

            // Dispose database connection
            db.Dispose();
        }

        /// <summary>
        /// Callback function that handles approval and blocking of dayplan records
        /// </summary>
        protected void callBackManageCustomerApproval_Callback(object sender, CallbackEventArgs e)
        {
            // Get values (0: Actionparameter, 1-X: Array of servicecarscheduledetailid's)
            string[] param = e.Parameter.Split(',');

            // Instantiate database
            TireServiceDB db = new TireServiceDB();

            // Validate action to take
            if (Convert.ToString(param[0]) == "RequestApproval")
            {
                for (int i = 1; i < param.Length; i++)
                {
                    SendConfirmationEmailToSelected(db, Convert.ToInt32(param[i]));
                }
            }
            if (Convert.ToString(param[0]) == "CustomerApproved")
            {
                for (int i = 1; i < param.Length; i++)
                {
                    CustomerApproved(db, Convert.ToInt32(param[i]), true);
                }
            }
            if (Convert.ToString(param[0]) == "RemoveApprovalOnSelected")
            {
                for (int i = 1; i < param.Length; i++)
                {
                    CustomerApproved(db, Convert.ToInt32(param[i]), false);
                }
            }
            if (Convert.ToString(param[0]) == "AddBlockOnSelected")
            {
                for (int i = 1; i < param.Length; i++)
                {
                    ServiceCarScheduleDetail detail = db.GetServiceCarScheduleDetail(Convert.ToInt32(param[i]));

                    if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.Available)
                    {
                        detail.ScheduleDetailTypeId = (int)Shared.ScheduleDetailType.Blocked;
                        detail.Note = "Tidsrum blokeret";
                    }
                }
            }

            // Commit changes to database
            db.SubmitChanges();

            // Dispose database connection
            db.Dispose();
        }

        /// <summary>
        /// Function that sends confirmation email to selected customer
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ServiceCarScheduleDetailId">Id on booking to send email for</param>
        private void SendConfirmationEmailToSelected(TireServiceDB db, int ServiceCarScheduleDetailId)
        {
            // Fecth detail
            ServiceCarScheduleDetailView detail = db.ServiceCarScheduleDetailViews.SingleOrDefault(p => p.ServiceCarScheduleDetailId == ServiceCarScheduleDetailId);

            if (detail != null)
            {
                //if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.TireChange)
                if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
                {
                    // Send email
                    SendConfirmationEmail(db, detail);
                }
            }
        }

        /// <summary>
        /// Function that change confirmation on servicedetail for customer
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ServiceCarScheduleDetailId">Id on booking to set as customer confirmed/not confirmed</param>
        /// <param name="CustomerConfirmed">True/False value indicating if customer confirmed booking</param>
        private void CustomerApproved(TireServiceDB db, int ServiceCarScheduleDetailId, bool CustomerConfirmed)
        {
            // Fecth detail to update
            ServiceCarScheduleDetail detail = db.GetServiceCarScheduleDetail(ServiceCarScheduleDetailId);

            if (detail != null)
            {
                //if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.TireChange)
                if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
                {
                    // Update detail
                    detail.CustomerConfirmed = CustomerConfirmed;
                }
            }
        }

        /// <summary>
        /// Function that sends email to customer for a specific servicedetail
        /// </summary>
        /// <param name="db">Database connection</param>
        /// <param name="scheduledetail">Servicedetail</param>
        private void SendConfirmationEmail(TireServiceDB db, ServiceCarScheduleDetailView scheduledetail)
        {
            string CustomerApprovalLink = ConfigurationManager.AppSettings["CustomerConfirmationURL"].ToString() + "?ApprovalId=" + scheduledetail.DetailGuid.ToString() + "&CID=" + scheduledetail.CustomerId.ToString();
            string CustomerDisapprovalLink = ConfigurationManager.AppSettings["CustomerConfirmationURL"].ToString() + "?ApprovalId=" + scheduledetail.DetailGuid.ToString() + "&Approve=false&CID=" + scheduledetail.CustomerId.ToString();

            EmailNotificationServices emailService = new EmailNotificationServices();
            emailService.BookServiceDrive_SendCustomerEmail(scheduledetail.Email, scheduledetail.Name, db.GetCarRegistrationNumber(Convert.ToInt32(scheduledetail.CarId)), scheduledetail.TireTypeDescription, scheduledetail.ScheduleDate.ToShortDateString(), scheduledetail.StartTime.ToString() + "-" + scheduledetail.EndTime.ToString(), scheduledetail.ToAddress, scheduledetail.ToZipCode, scheduledetail.ToCity, scheduledetail.CustomerId.ToString(), scheduledetail.SubscriptionId.ToString(), scheduledetail.CustomerSubscriptionId.ToString(), CustomerApprovalLink, CustomerDisapprovalLink); 

            //// Send email
            //SendEmail(scheduledetail.Email, scheduledetail.Name, db.GetCarRegistrationNumber(Convert.ToInt32(scheduledetail.CarId)), scheduledetail.TireTypeDescription, scheduledetail.ScheduleDate.ToShortDateString(), scheduledetail.StartTime.ToString() + "-" + scheduledetail.EndTime.ToString(), scheduledetail.ToAddress, scheduledetail.ToZipCode, scheduledetail.ToCity, scheduledetail.DetailGuid.ToString(), scheduledetail.CustomerId.ToString(), scheduledetail.SubscriptionId.ToString(), scheduledetail.CustomerSubscriptionId.ToString());

            // Update serviceschedule detail
            ServiceCarScheduleDetail updatescheduledetail = db.GetServiceCarScheduleDetail(scheduledetail.ServiceCarScheduleDetailId);
            updatescheduledetail.CustomerEmailSendCount = updatescheduledetail.CustomerEmailSendCount + 1;
        }

        ///// <summary>
        ///// Function that sends email to customer with planned service date, time and location and link for confirming or declining planned service
        ///// </summary>
        ///// <param name="CustomerEmail">Customer email that this email will be send to</param>
        ///// <param name="CustomerName">Name on customer</param>
        ///// <param name="RegistrationNumber">RegistrationNumber on car</param>
        ///// <param name="TireSetType">Tiretype description (Winther/Summer)</param>
        ///// <param name="ScheduleDate">Scheduledate for the service</param>
        ///// <param name="TimeSpan">Timespan for the service</param>
        ///// <param name="Address">Address for service</param>
        ///// <param name="ZipCode">ZipCode for service</param>
        ///// <param name="City">City for service</param>
        ///// <param name="DetailGuid">Unik id for serviceschedule detail - used in email links</param>
        //private void SendEmail(string CustomerEmail, string CustomerName, string RegistrationNumber, string TireSetType, string ScheduleDate, string TimeSpan, string Address, string ZipCode, string City, string DetailGuid, string CustomerId, string SubscriptionId, string CustomerSubscriptionId)
        //{
        //    string Subject = "Booking af tid til hjulskift (Abonnement " + CustomerId + "-" + SubscriptionId + "-" + CustomerSubscriptionId + ")";
        //    string CustomerApprovalLink = ConfigurationManager.AppSettings["CustomerConfirmationURL"].ToString() + "?ApprovalId=" + DetailGuid;
        //    string CustomerDisapprovalLink = ConfigurationManager.AppSettings["CustomerConfirmationURL"].ToString() + "?ApprovalId=" + DetailGuid + "&Approve=false";
        //    bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));

        //    EmailNotification.EmailNotification message = new EmailNotification.EmailNotification();

        //    Shared email = new Shared();

        //    MembershipUser user = Membership.GetUser();

        //    // Send email to customer with tire set pattern witth us on bcc
        //    email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), message.SendServiceCarScheduleDetailBooking(CustomerName, RegistrationNumber, TireSetType, ScheduleDate, TimeSpan, Address, ZipCode, City, CustomerApprovalLink, CustomerDisapprovalLink), Subject, true, test, user.Email, null, null, Convert.ToInt32(CustomerId), new Guid(user.ProviderUserKey.ToString()));
        //}

        /// <summary>
        /// Callback function that saves manual edit of servicedetail
        /// </summary>
        protected void callBackSaveServiceDetail_Callback(object sender, CallbackEventArgs e)
        {
            string[] param = e.Parameter.Split('|');

            // Instantiate database
            TireServiceDB db = new TireServiceDB();

            // Fecth detail to update
            ServiceCarScheduleDetail detail = db.GetServiceCarScheduleDetail(Convert.ToInt32(param[0]));

            if (detail != null)
            {
                //if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive | detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.TireChange)

                if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
                {
                    detail.ToAddress = param[1].ToString();
                    detail.ToZipCode = param[2].ToString();
                    detail.ToCity = param[3].ToString();
                    detail.StartTime = TimeSpan.Parse(param[4]);
                    detail.EndTime = TimeSpan.Parse(param[5]);
                    detail.ToLatitude = double.Parse(param[6]);
                    detail.ToLongitude = double.Parse(param[7]);
                }
            }

            // Commit changes to database
            db.SubmitChanges();

            // Rebind gridview
            LoadDayPlan(detail.ServiceCarId, detail.ScheduleDate);

            // Dispose database connection
            db.Dispose();
        }
    }
}